<?php

namespace VSF\Console\Command;

use Symfony\Component\Console\Input\InputArgument,
    Symfony\Component\Console\Input\InputOption,
    Symfony\Component\Console,
    Doctrine\ORM\Tools\Console\MetadataFilter,
    Doctrine\ORM\Tools\EntityGenerator,
    Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;

/**
 * Command to generate entity classes and method stubs from your mapping information.
 *
 * @link    www.vsf.vankata-bg.com
 * @author  Ivan Atanasov <i.atanasov77@gmail.com>
 */
class CreateModuleCommand extends Console\Command\Command
{
	
	private $_modulePath;
	private $_moduleTemplate;
	
    /**
     * @see Console\Command\Command
     */
    protected function configure()
    {
        $this->setName('vsf:create-module')
	        ->setDescription('Generate entity classes and method stubs from your mapping information.')
	        ->setDefinition(array(
	            new InputArgument(
	                'name', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
	                'A string pattern used to match entities that should be processed.'
	            )
	        ));
	    
	    
	    $this->setHelp(<<<EOT
No Help!
EOT
	    		);
    }

    /**
     * @see Console\Command\Command
     */
    protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
    {
    	$moduleName = $input->getArgument('name');
    	$this->_modulePath = APPLICATION_PATH . '/module/' . $moduleName;
    	$this->_templatePath = __DIR__ . '/Templates/Module';
    	
        system("mkdir {$this->_modulePath} -p");
		$this->_copyTemplate($this->_templatePath, $moduleName);
    }
    
    private function _copyTemplate($directory, $module)
    {
    	$moduleLower = strtolower($module);
    	$currentDirectory = dir($directory);
    
    	while ($entry = $currentDirectory->read()) {
    		if ($entry != "." && $entry != ".." && $entry != ".svn") {
    			$newEntry = substr($directory . '/' . $entry, strlen($this->_templatePath));
    			$newEntry = str_replace("template", $moduleLower, $newEntry);
    			$newEntry = str_replace("Template", $module, $newEntry);
    			
    			if (is_dir($directory."/".$entry)) {
    				system("mkdir {$this->_modulePath}/{$newEntry} -p");
    				$this->_copyTemplate($directory."/".$entry, $module);
    			}
    			else {
    				$template = file_get_contents($directory . "/" . $entry);
    				$template = str_replace('{$module}', $module, $template);
    				$template = str_replace('{$moduleLower}', $moduleLower, $template);
    				file_put_contents($this->_modulePath.'/'.$newEntry, $template);
    			}
    		}
    	}
    
    	$currentDirectory->close();
    }
    
}
